﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Collections;

namespace Billder
{
    public partial class BOM : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated) {
                Response.Redirect("Account/login.aspx");
            }
            if (Request.HttpMethod == "GET" && Request.QueryString.AllKeys.Contains("q"))
            {
                ShowTable();
            }
            else
            {
                switch (txtAction.Value)
                {
                    case "prepareEdit":
                        txtAction.Value = "commitEdit";
                        prepareEdit();
                        extraFields();
                        break;
                    case "none":
                        extraFields();
                        txtAction.Value = "new";
                        ClearForm();
                        break;
                    case "UploadImage":
                        uploadImage();
                        break;
                    case "commitEdit":
                        commitEdit();
                        break;
                    case "new":
                        AddBOM();
                        ClearForm();
                        break;
                }
            }
        }
        private void ShowTable()
        {
            List<OColumn> columns = new List<OColumn>();
            columns.Add(new OColumn("Assembly") { label = "Nombre" });
            columns.Add(new OColumn("Revision") { label = "Revision" });
            columns.Add(new OColumn("Description") { label = "Descripcion" });
            columns.Add(new OColumn("PhotoLink") { label = "Foto" });
            OTable t = new OTable("sp_cat_GetAssemblyRevision", columns);
            Response.Clear();
            StringBuilder sb = new StringBuilder();
            StringWriter tw = new StringWriter(sb);
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            t.getTable("PKPartMaster DESC","FKStatus NOT IN (2,5)", "PKPartMaster").RenderControl(hw);
            Response.Write(sb.ToString());
            Response.End();
        }
        private void AddBOM()
        {
            File.Move(System.Configuration.ConfigurationManager.AppSettings["tmpImagesDir"] + txtImgCode.Value, System.Configuration.ConfigurationManager.AppSettings["imagesDir"] + txtImgCode.Value);
            HandleAutocompletes();
            Hashtable ht = new Hashtable();
            ht.Add("PKAssembly", "0");
            ht.Add("Assembly", txtAssembly.Text);
            ht.Add("FKFamily", 1);
            ht.Add("UserUpdater", 1);
            int pkAssembly = Catalog.addSys("Assembly", ht);
            ht = new Hashtable();
            ht.Add("FKAssembly", pkAssembly);
            ht.Add("Revision", txtRevision.Text);
            ht.Add("LOH", txtLOH.Text);
            ht.Add("ValueAdded", txtProfit.Text);
            ht.Add("Description", txtDescription.Text);
            ht.Add("SalesQty", txtQty.Text);
            ht.Add("UserUpdater", "1");
            int pk = Catalog.addSys("AssemblyRevision", ht);
            string XML = Request.Form["txtBOM"].ToString();
            BL.BOM currentAssy = new BL.BOM(XML);
            foreach (BL.Part part in currentAssy.Parts) {
                if (part is BL.BOM) {
                    ht = new Hashtable();
                    ht.Add("FKAssemblyRevision", pk);
                    ht.Add("FKSubAssemblyRevision", part.ID);
                    ht.Add("Quantity", part.Qty);
                    ht.Add("UserUpdater", 1);
                    Catalog.addSys("SubAssembly", ht);
                }
                else {
                    ht = new Hashtable();
                    ht.Add("FKAssemblyRevision" , pk);
                    ht.Add("FKPartMaster", part.ID);
                    ht.Add("Quantity", part.Qty);
                    ht.Add("UserUpdater", 1);
                    Catalog.addSys( "BOM" , ht );
                }
            }
        }

        private void HandleAutocompletes()
        {
           // throw new NotImplementedException();
        }

        private void commitEdit()
        {
            if (!txtImgCode.Value.Equals(""))
            {
                File.Move(System.Configuration.ConfigurationManager.AppSettings["tmpImagesDir"] + txtImgCode.Value, System.Configuration.ConfigurationManager.AppSettings["imagesDir"] + txtImgCode.Value);
            }
            Hashtable ht = new Hashtable();
            ht.Add("PKAssembly", txtFKAssembly.Value);
            ht.Add("Assembly", txtAssembly.Text);
            ht.Add("FKFamily", 1);
            ht.Add("UserUpdater", 1);
            
            Catalog.addSys("Assembly", ht);
            ht = new Hashtable();
            ht.Add("PKAssemblyRevision", txtPKBOM.Value);
            ht.Add("Revision", txtRevision.Text);
            ht.Add("LOH", txtLOH.Text);
            ht.Add("ValueAdded", txtProfit.Text);
            ht.Add("Description", txtDescription.Text);
            ht.Add("SalesQty", txtQty.Text);
            ht.Add("UserUpdater", "1");
            int pk = Catalog.addSys("AssemblyRevision", ht);
            ht = new Hashtable();
            ht.Add("FKAssemblyRevision" , txtPKBOM.Value);
            Catalog.del("BOM" , ht , true);
            string XML = Request.Form["txtBOM"].ToString();
            BL.BOM currentAssy = new BL.BOM(XML);
            foreach (BL.Part part in currentAssy.Parts)
            {
                if (part is BL.BOM)
                {
                    ht = new Hashtable();
                    ht.Add("FKAssemblyRevision", txtPKBOM.Value);
                    ht.Add("FKSubAssemblyRevision", part.ID);
                    ht.Add("Quantity", part.Qty);
                    ht.Add("UserUpdater", 1);
                    Catalog.addSys("SubAssembly", ht);
                }
                else
                {
                    ht = new Hashtable();
                    ht.Add("FKAssemblyRevision", txtPKBOM.Value);
                    ht.Add("Quantity", part.Qty);
                    ht.Add("FKPartMaster", part.ID);
                    ht.Add("UserUpdater", 1);
                    Catalog.addSys("BOM", ht);
                }
            }
        }

        private void ClearForm()
        {
            txtAssembly.Text = "";
            txtRevision.Text = "";
            txtSalesQty.Text = "";
            txtPartNumber.Text = "";
            txtQty.Text = "";
            txtLOH.Text = "";
            txtProfit.Text = "";
            txtDescription.Text = "";
        }

        private void extraFields()
        {

            if (User.Identity.Name.Equals("Demetrio"))
            {
                txtLOH.Enabled = true;
                txtLOH.CssClass = txtLOH.CssClass.Replace("disabled", "");
                txtProfit.Enabled = true;
                txtProfit.CssClass = txtProfit.CssClass.Replace("disabled", "");
                btnApprove.Enabled = true;
            }
            else
            {
                txtLOH.Enabled = false;
                txtLOH.CssClass += txtLOH.CssClass.Contains("disabled") ? "" : " disabled";
                txtProfit.Enabled = false;
                txtProfit.CssClass += txtProfit.CssClass.Contains("disabled") ? "" : " disabled";
                btnApprove.Enabled = false;
            }
        }

        private void prepareEdit()
        {
            DataTable dt = Catalog.getSys("BOM" , int.Parse(txtPKBOM.Value));
            txtAssembly.Text = dt.Rows[0]["Assembly"].ToString();
            txtRevision.Text = dt.Rows[0]["Revision"].ToString();
            txtDescription.Text = dt.Rows[0]["Description"].ToString();
            txtSalesQty.Text = dt.Rows[0]["SalesQty"].ToString();
            txtLOH.Text = dt.Rows[0]["LOH"].ToString();
            txtProfit.Text = dt.Rows[0]["ValueAdded"].ToString();
            txtFKAssembly.Value = dt.Rows[0]["FKAssembly"].ToString();
            BL.BOM b = new BL.BOM(int.Parse(txtPKBOM.Value) , txtAssembly.Text , 1 , txtRevision.Text,float.Parse(txtSalesQty.Text),float.Parse(txtLOH.Text),float.Parse(txtProfit.Text) ,txtDescription.Text);
            foreach( DataRow row in dt.Rows )
            {
                if (row["Item"].ToString().Equals ("PartMaster"))
                {
                    BL.Part p = new BL.Part(int.Parse(row["PKPartMaster"].ToString()), row["PartNumber"].ToString(), int.Parse(row["Quantity"].ToString()));
                    b.Parts.Add(p);
                }
                else {
                    BL.BOM sa = new BL.BOM(int.Parse(row["PKPartMaster"].ToString()), row["PartNumber"].ToString(), int.Parse(row["Quantity"].ToString()), row["Revision"].ToString(), 0, 0, 0, "");
                    b.Parts.Add(sa);
                }
            }
            later.InnerHtml = string.Format("<script>currentAssy = {0};$(\"#BOMDiv\").html(currentAssy.asHTML());$(\"#txtBOM\").text(currentAssy.asXML());</script>",b.asJS());
            
        }
        protected void uploadImage()
        {
            Request.Files["partImageFile"].SaveAs(System.Configuration.ConfigurationManager.AppSettings["tmpImagesDir"] + txtImgCode.Value + Request.Files["partImageFile"].FileName);
            Response.Clear();
            Response.Write("SUCCESS");
            Response.Write("<script>parent.refreshImg('" + txtImgCode.Value + Request.Files["partImageFile"].FileName + "');</script>");
            Response.End();
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            Hashtable ht;
            ht = new Hashtable();
            ht.Add("PKAssemblyRevision", txtPKBOM.Value);
            ht.Add("FKStatus", 3);
            ht.Add("UserUpdater", "1");
            int pk = Catalog.addSys("AssemblyRevision", ht);
        }
    }
}